import { createRouter, createWebHistory } from "vue-router";
import NotFoundPage from "@/pages/NotFoundPage.vue";
import store from '@/store';
import { pathToCamel } from '@/utils/tool';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { ElMessage } from "element-plus";
const { BASE_URL, VITE_PREFIX } = import.meta.env;
NProgress.configure({
	showSpinner: false, // 是否显示加载ico
})
const routes = [
	{
		path: '/redirect',
		component: () => import('@/layout/index.vue'),
		children: [
			{
				path: '/redirect/:path(.*)',
				component: () => import('@/layout/Router/Redirect.vue')
			},
			{
				path: '/ExistingEvidence/DocumentAdd',
				name: "文件存证",
				component: () => import('@/pages/ExistingEvidence/DocumentAdd.vue')
			},
			{
				path: '/ExistingEvidence/DocumentDetail',
				name: "文件存证明细",
				component: () => import('@/pages/ExistingEvidence/DocumentDetail.vue')
			},
			{
				path: '/ExistingEvidence/DataAdd',
				name: "数据存证",
				component: () => import('@/pages/ExistingEvidence/DataAdd.vue')
			},
			{
				path: '/ExistingEvidence/DataDetail',
				name: "数据存证明细",
				component: () => import('@/pages/ExistingEvidence/DataDetail.vue')
			},
			{
				path: '/EbtainEvidence/EvidenceDetail',
				name: "取证明细",
				component: () => import('@/pages/EbtainEvidence/EvidenceDetail.vue')
			}
		]
	},
	{
		path: '/login',
		component: () => import('@/pages/Login.vue')
	},
	{
		path: '/oauth',
		component: () => import('@/pages/Oauth.vue')
	},
	{
		path: '/404',
		name: "Page not found",
		component: NotFoundPage
	}
];
export const errorRoute = {
	path: '/:pathMatch(.*)',
	redirect: '/404'
}

export const router = createRouter({
	history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
	routes
});
// export default router 增加下面代码，添加一个临时路由
// if (!router.hasRoute()) {
// 	router.addRoute({
// 		path: window.location.pathname,
// 		name: 'TempRoute',
// 		component: () => import('@/layout/index.vue')
// 	})
// }

const asyncRoutes = {
	path: '/',
	component: () => import('@/layout/index.vue'),
	redirect: '/Home',
	children: [
		{
			path: '/Home',
			name: 'Home',
			component: () => import('@/pages/Home.vue'),
			meta: {
				title: 'Home',
			}
		},
	]
}
const whiteList = ['/login','/oauth']

// 路由加载前
router.beforeEach(async (to, from, next) => {
	NProgress.start()
	// token存在的情况
	if (store.userStore.token) {
		if (to.path === '/login' || to.path === '/oauth') {
			next('/Home');
		} else {
			// 用户信息不存在，则重新拉取用户等信息
			if (!store.userStore.user.userId) {
				try {
					let data = await store.userStore.getUserInfoAction();
					// 用户信息获取不到，抛出错误，不然路由守卫逻辑会无限循环
					if (data.data === '') {
						throw new userInfoError('');
					}
					const menuRoutes = await store.routerStore.getMenuRoutes();
					// 菜单信息获取不到，抛出错误，不然路由守卫逻辑会无限循环
					if (!menuRoutes) {
						throw new menuRoutesError('');
					}
					// 根据后端菜单路由，生成KeepAlive路由
					const keepAliveRoutes = getKeepAliveRoutes(menuRoutes, []);


					// 添加菜单路由
					asyncRoutes.children?.push(...keepAliveRoutes);

					// // 增加以下代码，判断是否存在临时路由，存在则删除
					// if (router.hasRoute('TempRoute')) {
					// 	router.removeRoute('TempRoute')
					// }
					router.addRoute(asyncRoutes);

					// 错误路由
					router.addRoute(errorRoute);

					// 保存路由数据
					// store.routerStore.setRoutes(routes.concat(asyncRoutes))

					// 搜索菜单需要使用
					// store.routerStore.setSearchMenu(keepAliveRoutes)
					next({...to, replace: true })

					// 此时已添加了后端返回的动态路由，进行跳转一次
					// next({ path: to.path, replace: true })

				} catch (err) {
					// 过程中发生任何错误，都直接重置 Token，并重定向到登录页面
					store.userStore.logoutAction();
					next("/login");
					NProgress.done();
				}

			} else {
				next()
			}
		}
	} else {
		// 没有token的情况下，可以进入白名单
		if (whiteList.indexOf(to.path) > -1) {
			next()
		} else {
			next('/login')
		}
	}
})
// 路由加载后
router.afterEach(() => {
	NProgress.done()
})


// 获取扁平化路由，将多级路由转换成一级路由
export const getKeepAliveRoutes = (rs = [], breadcrumb) => {
	const routerList = []

	rs.forEach((item) => {
		if (item.meta.title) {
			breadcrumb.push(item.meta.title)
		}

		if (item.children && item.children.length > 0) {
			routerList.push(...getKeepAliveRoutes(item.children, breadcrumb))
		} else {
			item.meta.breadcrumb.push(...breadcrumb)
			routerList.push(item)
		}

		breadcrumb.pop()
	})
	return routerList
}

// 加载vue组件
const layoutModules = import.meta.glob('/src/pages/**/*.vue')

// 根据路径，动态获取vue组件
const getDynamicComponent = (path) => {
	const component = layoutModules[`/src/pages/${path}.vue`]
	if (!component) {
		console.error('component error', path)
	}
	return component
}

// 根据菜单列表，生成路由数据
export const generateRoutes = (menuList) => {
	const routerList = [];

	menuList.forEach((menu) => {
		let component
		let path
		if (menu.children && menu.children.length > 0) {
			component = () => import('@/layout/index.vue')
			path = '/' + menu.menuPath
		} else {
			component = getDynamicComponent(menu.menuPath)
			path = '/' + menu.menuPath
		}
		const route = {
			path: path,
			name: pathToCamel(path),
			component: component,
			children: [],
			meta: {
				title: menu.menuName,
				icon: menu.menuIcon,
				id: '' + menu.menuId,
				breadcrumb: []
			}
		}

		// 有子菜单的情况
		if (menu.children && menu.children.length > 0) {
			route.children?.push(...generateRoutes(menu.children))
		}

		routerList.push(route)
	})

	return routerList
}
